<?php

/**
 * 响应封装
 *
 * Author: Surfin
 * Datetime: 16/10/20 下午2:21
 */

namespace Utils;

use Symfony\Component\HttpFoundation\Response;

class Responses extends Response
{
    const RESPONSE_JSON = 'json';
    const RESPONSE_XML = 'xml';
    const RESPONSE_ARRAY = 'array';
    const RESPONSE_UNKNOWN = 'unknown';

    /**
     * 返回值处理
     *
     * @param int $errorCode
     * @param string $message
     * @param array $data
     * @param string $type
     * @return array|Response
     */
    private static function value($message = '', $errorCode = 0, array $data = array(), $type = self::RESPONSE_JSON)
    {
        $result = array('errorCode' => $errorCode, 'message' => $message, 'data' => $data);

        if ( $type == self::RESPONSE_JSON ) { // json 格式
            $response = new Response(json_encode($result));
            $response->headers->set('Content-Type', 'application/json');

            return $response;
        } else if ( $type == self::RESPONSE_XML ) { // 返回xml数据

            $xml = '<?xml version="1.0" encoding="UTF-8"?>';
            $response = new Response($xml);
            $response->headers->set('Content-Type', 'xml');

            return $response;
        } else if ( $type = self::RESPONSE_ARRAY ) { // 返回数组array

            return $result;
        }
        // 未知的情况下，直接打印
        var_dump($result); exit;
    }

    /**
     * 返回json
     *
     * @param string $message
     * @param int $errorCode
     * @param array $data
     * @return array|Response
     */
    public static function json($message = '', $errorCode = 0, array $data = array())
    {
        return self::value($message, $errorCode, $data);
    }

    /**
     * 返回xml数据
     *
     * @param string $message
     * @param int $errorCode
     * @param array $data
     * @return array|Response
     */
    public static function xml($message = '', $errorCode = 0, array $data = array())
    {
        return self::value($message, $errorCode, $data, self::RESPONSE_XML);
    }

    /**
     * 返回数组
     *
     * @param string $message
     * @param int $errorCode
     * @param array $data
     * @return array|Response
     */
    public static function arrays($message = '', $errorCode = 0, array $data = array())
    {
        return self::value($message, $errorCode, $data, self::RESPONSE_XML);
    }

    /**
     * 测试模式/未知模式
     *
     * @param string $message
     * @param int $errorCode
     * @param array $data
     * @return array|Response
     */
    public static function debug($message = '', $errorCode = 0, array $data = array())
    {
        return self::value($message, $errorCode, $data, self::RESPONSE_ARRAY);
    }


}
